﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Text;

namespace LiteBlog.Common.Components
{
    public class UrlValidAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return IsValidUrl((string)value);
        }

        private bool IsValidUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return true;

            HttpWebResponse res;
            try
            {
                Uri uri = new Uri(url, UriKind.Absolute);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                res = (HttpWebResponse)req.GetResponse();
            }
            catch
            {
                return false;
            }

            switch (res.StatusCode)
            {
                case HttpStatusCode.OK:
                case HttpStatusCode.Redirect:
                case HttpStatusCode.RedirectKeepVerb:
                case HttpStatusCode.RedirectMethod:
                    return true;
            }

            return false;
        }
    }
}
